import sys
import os

from PyQt6.QtWidgets import *
from PyQt6.QtCore import QThread, pyqtSignal
from 数据处理层 import bilibilivideodownload
from 业务逻辑层.ui import Ui_Form  # 假设 ui.py 是生成的界面文件
from 业务逻辑层 import music163download, webresource
import shutil


def list_files_in_folder(folder_path):
    file_paths = []
    try:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                file_paths.append(file_path)
        return file_paths
    except FileNotFoundError:
        print(f"错误：未找到文件夹 {folder_path}！")
    except Exception as e:
        print(f"错误：发生未知错误 {e}！")
    return []


def delete_files_in_folder(folder_path):
    try:
        if os.path.exists(folder_path):
            for root, dirs, files in os.walk(folder_path):
                for file in files:
                    file_path = os.path.join(root, file)
                    try:
                        os.remove(file_path)
                        print(f"已删除文件: {file_path}")
                    except Exception as e:
                        print(f"删除文件 {file_path} 时出错: {e}")
                for dir in dirs:
                    dir_path = os.path.join(root, dir)
                    try:
                        shutil.rmtree(dir_path)
                        print(f"已删除文件夹: {dir_path}")
                    except Exception as e:
                        print(f"删除文件夹 {dir_path} 时出错: {e}")
        else:
            print(f"错误：文件夹 {folder_path} 不存在！")
    except Exception as e:
        print(f"错误：发生未知错误 {e}！")


class DownloadImgThread(QThread):
    finished = pyqtSignal(list)

    def __init__(self, url):
        super().__init__()
        self.url = url

    def run(self):
        imgurl = webresource.image_download(self.url)
        webresource.image_download2(imgurl)
        self.finished.emit(imgurl)
class DownloadVideoThread(QThread):
    finished = pyqtSignal(str,str,str,str)
    def __init__(self, url):
        super().__init__()
        self.url = url

    def run(self):
        title,vd_url,ad_url = bilibilivideodownload.bilibilivideo(self.url)
        imgurl = bilibilivideodownload.bilibilicover(self.url)
        print('imgurl:'+imgurl)
        self.finished.emit(imgurl,title,vd_url,ad_url)
class DownloadMusicThread(QThread):
    finished = pyqtSignal(str,str,str,str)
    def __init__(self, url):
        super().__init__()
        self.url = url

    def run(self):
        music_url,title= music163download.MusicUrl(self.url)
        cover_url = music163download.music_cover(self.url)
        vd_url="wu"
        self.finished.emit(cover_url,title,vd_url,music_url)
class DownloadTextThread(QThread):
    finished = pyqtSignal(str,str)
    def __init__(self, url):
        super().__init__()
        self.url = url

    def run(self):
        title,body_text= webresource.text_download(self.url)
        self.finished.emit(title,body_text)
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.handle_button_click)


    def handle_button_click(self):
        selected_platform = self.ui.comboBox.currentText()
        url = self.ui.lineEdit.text()

        if selected_platform == "哔哩哔哩视频":
            self.handle_bilibili(url)
        elif selected_platform == "网易云音乐":
            self.handle_music163(url)
        elif selected_platform == "网页图片":
            self.handle_web_images(url)
        elif selected_platform == "网页正文":
            self.handle_web_text(url)

        self.ui.lineEdit.clear()

    def handle_bilibili(self, url):
        if url.startswith('https://www.bilibili.com/video'):
            self.ui.clear_images()
            if self.ui.label_14:
                self.ui.label_14.setText("加载中")
            self.download_thread = DownloadVideoThread(url)
            self.download_thread.finished.connect(self.on_download_finished)
            self.download_thread.start()
        elif not url:
            QMessageBox.warning(self, '警告', '输入不能为空！')
        else:
            QMessageBox.warning(self, '警告', '输入的链接不对请重新输入！')
    def on_bilibli_download(self, url):
        pass
    def handle_music163(self, url):
        if url.startswith('https://music.163.com/#/song?id='):
            self.ui.clear_images()
            if self.ui.label_14:
                self.ui.label_14.setText("加载中")
            self.download_thread = DownloadMusicThread(url)
            self.download_thread.finished.connect(self.on_download_finished)
            self.download_thread.start()
        elif not url:
            QMessageBox.warning(self, '警告', '输入不能为空！')
        else:
            QMessageBox.warning(self, '警告', '输入的链接不对请重新输入！')

    def handle_web_images(self, url):
        if url.startswith('http'):
            self.ui.clear_images()
            if self.ui.label_14:
                self.ui.label_14.setText("加载中")
            self.download_thread = DownloadImgThread(url)
            self.download_thread.finished.connect(self.on_download_finished)
            self.download_thread.start()
        elif not url:
            QMessageBox.warning(self, '警告', '输入不能为空！')
        else:
            QMessageBox.warning(self, '警告', '输入的链接不对请重新输入！')

    def on_download_finished(self,imgurl,title="wu",vd_url='wu',ad_url='wu'):
        print(imgurl)
        folder_path = '../临时'
        image_paths = list_files_in_folder(folder_path)
        i=0
        for image_path in image_paths:
            self.ui.add_image_to_flow(image_path,imgurl[i],title,vd_url,ad_url)
            i+=1
        delete_files_in_folder(folder_path)
        if self.ui.label_14:
            self.ui.label_14.setText("加载完成")

    def handle_web_text(self, url):
        if url.startswith('http'):
            self.ui.clear_images()
            if self.ui.label_14:
                self.ui.label_14.setText("加载中")
            self.download_thread = DownloadTextThread(url)
            self.download_thread.finished.connect(self.on_text_finished)
            self.download_thread.start()


        elif not url:
            QMessageBox.warning(self, '警告', '输入不能为空！')
        else:
            QMessageBox.warning(self, '警告', '输入的链接不对请重新输入！')
    def on_text_finished(self,title,body_text):
        self.ui.add_text_to_flow(title,body_text)
        if self.ui.label_14:
            self.ui.label_14.setText("加载完成")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
